package com.lagou.v4.container;

import com.lagou.v4.LifeCycle;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Kirito
 * @description:
 * @date 2020/05/02
 */
public class Server implements LifeCycle {

    private List<Service> services;

    @Override
    public void init() throws Exception {
        services = getServices();
        for (Service service : services) {
            service.init();
        }
    }

    private List<Service> getServices() throws DocumentException {
        InputStream resource = Server.class.getClassLoader().getResourceAsStream("server.xml");
        Element rootElement = new SAXReader().read(resource).getRootElement();
        List<Element> elements = rootElement.selectNodes("//Service");
        List<Service> serviceList = new ArrayList<>(elements.size());
        for (Element element : elements) {
            Service service = new Service();
            service.setElement(element);
            serviceList.add(service);
        }
        return serviceList;
    }

    // 解析server.xml配置文件
    public void load() {
        try {
            init();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void start() throws Exception {
        for (Service service : services) {
            service.start();
        }
    }
}
